import { v4 as uuid } from 'uuid';
import insert from './atom/db/insert';
import query from './atom/db/query';
import del from './atom/db/del';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	exam_id: string;
}

function get_week(d: number) {
	switch (d) {
		case 0:
			return '星期天';
		case 1:
			return '星期一';
		case 2:
			return '星期二';
		case 3:
			return '星期三';
		case 4:
			return '星期四';
		case 5:
			return '星期五';
		case 6:
			return '星期六';
		default:
			return '未知';
	}
}

async function atom(msg: Message) {
	const systemid = '5981';
	const query_obj = query(action_id, session_id, spaceid, systemid);

	query_obj.prepare('exam', ['_id', 'exam_name', 'exam_id', 'start_date', 'finish_date', 'days', 'am_start_time', 'pm_start_time'], { exam_id: msg.exam_id }, 1, 1);
	query_obj.prepare('exam_date', ['_id', 'exam_name', 'exam_id', 'exam_data', 'finish_date', 'days', 'am_start_time', 'pm_start_time'], { exam_id: msg.exam_id });

	const [q_data, ed_data] = await query_obj.exec();

	let start_date = (q_data[0] as any).start_date;
	const finish_date = (q_data[0] as any).finish_date;
	const exam_name = (q_data[0] as any).exam_name;

	function check_exam_date(exam_data: number) {
		const d = ed_data.filter((item: any) => {
			return item.exam_data === exam_data;
		});
		if (d.length > 0) {
			return true;
		} else {
			return false;
		}
	}
	const i_d = [];
	let flag = true;
	while (flag) {
		if (start_date === finish_date) {
			if (!check_exam_date(finish_date)) {
				const d = new Date(finish_date).getDay();
				i_d.push({ _id: uuid(), exam_id: msg.exam_id, exam_name, exam_data: finish_date, fzno: 0, is_deal: false, distribute_state: '未分配', week: get_week(d) });
			}
			flag = false;
		} else {
			if (!check_exam_date(start_date)) {
				const d = new Date(start_date).getDay();
				i_d.push({ _id: uuid(), exam_id: msg.exam_id, exam_name, exam_data: start_date, fzno: 0, is_deal: false, distribute_state: '未分配', week: get_week(d) });
			}
			start_date = start_date + 24 * 60 * 60 * 1000;
		}
	}

	const { prepare, exec } = insert(action_id, session_id, spaceid, systemid);
	prepare('exam_date', i_d);
	const ret = await exec();
	if (ret.code === 1) {
		const del_obj = del(action_id, session_id, spaceid, systemid);
		del_obj.prepare('exam_date', [{ $or: [{ exam_data: { $gt: finish_date } }, { exam_data: { $lt: (q_data[0] as any).start_date } }] } as any]);
		const d_res = await del_obj.exec();
		if (d_res.code === 1) {
			return 'success';
		} else {
			return 'fail';
		}
	} else {
		return 'fail';
	}
}
